<template>
  <el-card class="main-card">
    <div class="title">{{ this.$route.name }}</div>
    <!-- 文章标题 -->
    <div class="article-title-container">
      <el-input
        v-model="article.title"
        size="medium"
        placeholder="输入文章标题"
      />
      <el-button
        type="danger"
        size="medium"
        class="save-btn"
        @click="saveArticleDraft"
        v-if="article.id == null || article.status == 3"
      >
        保存草稿
      </el-button>
      <el-button
        type="danger"
        size="medium"
        @click="openModel()"
        style="margin-left: 10px"
      >
        发布文章
      </el-button>
    </div>
    <!-- 文章内容 -->
    <mavon-editor
      ref="md"
      v-model="article.content"
      @imgAdd="uploadImg"
      style="height: calc(100vh - 260px)"
    />
    <!-- 添加文章对话框 -->
    <el-dialog :visible.sync="addOrEdit" width="40%" top="3vh">
      <div class="dialog-title-container" slot="title">发布文章</div>
      <!-- 文章数据 -->
      <el-form label-width="80px" size="medium" :model="article">
        <!-- 文章分类 -->
        <el-form-item label="文章分类">
          <el-select v-model="article.categoryName" placeholder="请选择分类">
            <el-option
              v-for="c in categoryList"
              :key="c.id"
              :label="c.name"
              :value="c.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 文章标签 -->
        <el-form-item label="文章标签">
          <el-select
            v-model="article.tagNameList"
            multiple
            placeholder="请选择标签"
          >
            <el-option
              v-for="tag in tagList"
              :key="tag.id"
              :label="tag.name"
              :value="tag.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章类型">
          <el-select v-model="article.articleType" placeholder="请选择类型">
            <el-option
              v-for="item in typeList"
              :key="item.type"
              :label="item.desc"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
        <!-- 文章类型 -->
        <el-form-item label="原文地址" v-if="article.articleType != 0">
          <el-input
            v-model="article.originalUrl"
            placeholder="请填写原文链接"
          />
        </el-form-item>
        <!-- action="http://127.0.0.1:7777/admin/article/images" -->
        <el-form-item label="上传封面">
          <el-upload
            class="upload-cover"
            drag
            action="/api/admin/article/images"
            multiple
            :before-upload="beforeUpload"
            :on-success="uploadCover"
          >
            <i class="el-icon-upload" v-if="article.cover == ''" />
            <div class="el-upload__text" v-if="article.cover == ''">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <img v-else :src="article.cover" width="360px" height="180px" />
          </el-upload>
        </el-form-item>
        <el-form-item label="置顶">
          <el-switch
            v-model="article.isTop"
            active-color="#13ce66"
            inactive-color="#F4F4F5"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="发布形式">
          <el-radio-group v-model="article.status">
            <el-radio :label="1">公开</el-radio>
            <el-radio :label="2">私密</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addOrEdit = false">取 消</el-button>
        <el-button type="danger" @click="saveOrUpdateArticle">
          发 表
        </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
  
  <script>
import * as imageConversion from "image-conversion";
import tagApi from "@/api/tag";
import categoryApi from "@/api/category";
import articleApi from "@/api/article";
export default {
  created() {
    const path = this.$route.path;
    const arr = path.split("/");
    const articleId = arr[2];
    if (articleId) {
      articleApi.getBackArticleById(articleId).then((res) => {
        this.article = res.data;
      });
    } else {
      const article = sessionStorage.getItem("article");
      if (article) {
        this.article = JSON.parse(article);
      }
    }
    this.listCategories();
    this.listTags();
  },
  destroyed() {
    //文章自动保存功能
    this.autoSaveArticle();
  },
  data() {
    return {
      addOrEdit: false,
      autoSave: true,
      categoryList: [],
      tagList: [],
      typeList: [
        {
          type: 0,
          desc: "原创",
        },
        {
          type: 1,
          desc: "转载",
        },
      ],
      article: {
        id: null,
        title: "",
        content: "",
        cover: "",
        categoryName: null,
        tagNameList: [],
        originalUrl: "",
        isTop: 0,
        articleType: 0,
        status: 1,
      },
    };
  },
  methods: {
    // 获取分类列表
    listCategories() {
      categoryApi.categoryList().then(({ data }) => {
        this.categoryList = data;
      });
    },
    // 获取标签列表
    listTags() {
      tagApi.tagList().then(({ data }) => {
        this.tagList = data;
      });
    },
    openModel() {
      if (this.article.title.trim() == "") {
        this.$message.error("文章标题不能为空");
        return false;
      }
      if (this.article.content.trim() == "") {
        this.$message.error("文章内容不能为空");
        return false;
      }
      this.addOrEdit = true;
    },
    // 更新封面
    uploadCover(response) {
      this.article.cover = response.data;
    },
    // 文件上传前压缩
    beforeUpload(file) {
      return new Promise((resolve) => {
        if (file.size / 1024 < this.config.UPLOAD_SIZE) {
          resolve(file);
        }
        // 压缩到200KB,这里的200就是要压缩的大小,可自定义
        imageConversion
          .compressAccurately(file, this.config.UPLOAD_SIZE)
          .then((res) => {
            resolve(res);
          });
      });
    },
    // 上传图片
    uploadImg(pos, file) {
      var formdata = new FormData();
      if (file.size / 1024 < this.config.UPLOAD_SIZE) {
        formdata.append("file", file);
        articleApi.savaArticleImg(formdata).then((data) => {
          this.$refs.md.$img2Url(pos, data.data);
        });
      } else {
        // 压缩到200KB,这里的200就是要压缩的大小,可自定义
        imageConversion
          .compressAccurately(file, this.config.UPLOAD_SIZE)
          .then((res) => {
            formdata.append(
              "file",
              new window.File([res], file.name, { type: file.type })
            );
            articleApi.savaArticleImg(formdata).then((data) => {
              this.$refs.md.$img2Url(pos, data);
            });
          });
      }
    },
    // 保存文章草稿
    saveArticleDraft() {
      if (this.article.title.trim() == "") {
        this.$message.error("文章标题不能为空");
        return false;
      }
      if (this.article.content.trim() == "") {
        this.$message.error("文章内容不能为空");
        return false;
      }
      this.article.status = 3;
      articleApi.saveOrUpdateArticle(this.article).then((data) => {
        if (data.flag) {
          if (this.article.id === null) {
            this.$store.commit("removeTab", "发布文章");
          } else {
            this.$store.commit("removeTab", "修改文章");
          }
          sessionStorage.removeItem("article");
          this.$router.push({ path: "/article-list/" });
          this.$notify.success({
            title: "成功",
            message: "保存草稿成功",
          });
        } else {
          this.$notify.error({
            title: "失败",
            message: "保存草稿失败",
          });
        }
      });

      //关闭自动保存功能
      this.autoSave = false;
    },
    // 新建或更新文章
    saveOrUpdateArticle() {
      if (this.article.title.trim() == "") {
        this.$message.error("文章标题不能为空");
        return false;
      }
      if (this.article.content.trim() == "") {
        this.$message.error("文章内容不能为空");
        return false;
      }
      if (this.article.categoryName == null) {
        this.$message.error("文章分类不能为空");
        return false;
      }
      if (this.article.tagNameList.length == 0) {
        this.$message.error("文章标签不能为空");
        return false;
      }
      if (this.article.cover.trim() == "") {
        this.$message.error("文章封面不能为空");
        return false;
      }
      articleApi.saveOrUpdateArticle(this.article).then((data) => {
        if (data.flag) {
          if (this.article.id === null) {
            this.$store.commit("removeTab", "发布文章");
          } else {
            this.$store.commit("removeTab", "修改文章");
          }
          sessionStorage.removeItem("article");
          this.$router.push({ path: "/article-list/" });
          this.$notify.success({
            title: "成功",
            message: data.message,
          });
        } else {
          this.$notify.error({
            title: "失败",
            message: data.message,
          });
        }
        this.addOrEdit = false;
      });
      //关闭自动保存功能
      this.autoSave = false;
    },
    // 自动上传文章
    autoSaveArticle() {
      if (
        this.autoSave &&
        this.article.title.trim() != "" &&
        this.article.content.trim() != "" &&
        this.article.id != null
      ) {
        articleApi.saveOrUpdateArticle(this.article).then((data) => {
          if (data.flag) {
            this.$notify.success({
              title: "成功",
              message: "自动保存成功",
            });
          } else {
            this.$notify.error({
              title: "失败",
              message: "自动保存失败",
            });
          }
        });
      }
      // 保存本地文章记录
      if (this.autoSave && this.article.id == null) {
        sessionStorage.setItem("article", JSON.stringify(this.article));
      }
    },
  },
};
</script>
  
  <style scoped>
.article-title-container {
  display: flex;
  align-items: center;
  margin-bottom: 1.25rem;
  margin-top: 2.25rem;
}
.save-btn {
  margin-left: 0.75rem;
  background: #fff;
  color: #f56c6c;
}
</style>
  